package murphy.validator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.health.exceptions.ValidatorLevelException;

import murphy.validator.constants.VConstants;

/**
 * @author DirkMurphy
 * 
 * @blog http://www.cnblogs.com/dirkmurphyjava/
 * 
 * @date
 */
public abstract class Validator
{
	private Log	log	= LogFactory.getLog(Validator.class);

	public Validator()
	{
		System.out.println("---------------------------Validator initialed");
	}

	/**
	 * @param desc
	 * @param fieldName
	 * @param fieldValue0
	 * @return String
	 * @throws ValidatorLevelException
	 * @introduction if return ""(blank String) , pass the validate,<br>
	 *               else filtered by validator
	 * */
	// @SuppressWarnings("unused")
	public String fieldValidate(FieldDesc desc, String fieldName,
			Object fieldValue0) throws ValidatorLevelException
	{
		log.info("---------------Validator working");
		String fieldType = desc.getType();
		/** IS STRING **/
		if (ClassUtils.isString(fieldType))
		{
			log.info("-----------a string");
			// check the not-null
			String fieldValue = (String) fieldValue0;
			if (desc.isRequired() == true)
			{
				if (fieldValue == null || fieldValue.trim().equals(""))
				{
					return VConstants.RETURN_NOT_NULL_INVALID + "--"
							+ fieldName;
				}
			}
			// check the length
			if (fieldValue != null)
			{
				if (fieldValue.trim().getBytes().length > desc.getMax_length())
				{
					return VConstants.RETURN_LENGTH_TOO_LONG_INVALID + "--"
							+ fieldName;
				}
				if (fieldValue.trim().getBytes().length < desc.getMin_length())
				{
					return VConstants.RETURN_LENGTH_TOO_SHORT_INVALID + "--"
							+ fieldName;
				}
			}
			return "";// pass the validate
		}
		/** IS NUMBER **/
		else if (ClassUtils.isNumber(fieldType))
		{
			log.info("-------a number");
			Number fieldValue = (Number) fieldValue0;
			Number minValue = desc.getMin_value();
			Number maxValue = desc.getMax_value();

			byte fieldValueByte = fieldValue.byteValue();
			byte minValueByte = minValue.byteValue();
			byte maxValueByte = maxValue.byteValue();
			if (desc.isRequired() == true)
			{
				if (null == fieldValue)
				{
					return VConstants.RETURN_NOT_NULL_INVALID + "--"
							+ fieldName;
				}
			}
			if (fieldValue != null)
			{
				if (fieldValueByte > maxValueByte)
				{
					return VConstants.RETURN_NUMBER_TOO_LARGE_INVALID + "--"
							+ fieldName;
				}
				else if (fieldValueByte < minValueByte)
				{
					return VConstants.RETURN_NUMBER_TOO_SMALL_INVALID + "--"
							+ fieldName;
				}
			}
			return "";
		}

		return "";
	}

	/**
	 * sub class will implement it
	 * 
	 * @throws Exception
	 * */
	public abstract String validate(Object obj) throws Exception;
}
